package com.samnative.pineapple.main;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.value.Config;
import com.samnative.pineapple.widget.LoadingDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ezy.ui.view.RoundButton;


/**
 * 收银台=>无SDK的收银台，走H5或小程序的支付方式
 */
public class ChoosePayActivity2 extends BaseActivity implements View.OnClickListener {


    private Context context;
    /**
     * 支付方式按钮
     */
    private LinearLayout llWeichat, llAlipay;
    /**
     * 支付订单号
     */
    private String orderNo;
    /**
     * 当前选中的支付类型
     */
    private Paytmethod currentPaymethod;
    /**
     * 是否已微信安装
     */
    private boolean isInstallWeiChat;
    /**
     * 显示勾选
     */
    private ImageView iv_choose_wechat, iv_choose_ali;
    /**
     * 订单类型 1商城 2实体店 3用户充值
     */
    private int orderType;
    /**
     * 总价显示
     */
    private TextView amount_tv;
    /**
     * 确认按钮
     */
    private RoundButton btn_pay;
    /**
     * 支付配置列表
     */
    private List<Paytmethod> paytmethods;

    /**
     * 是否需要查询订单状态
     */
    private boolean isCheckOrder;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_choosepay2;
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        context = this;
        paytmethods = new ArrayList<>();
        findViewById(R.id.tv_back).setOnClickListener(this);
        this.orderNo = getIntent().getStringExtra("orderNo");
        this.orderType = getIntent().getIntExtra("orderType", 1);

        btn_pay = (RoundButton) findViewById(R.id.btn_pay);
        btn_pay.setOnClickListener(this);
        llWeichat = (LinearLayout) findViewById(R.id.ll_pay_weichat);
        llWeichat.setOnClickListener(this);
        llAlipay = (LinearLayout) findViewById(R.id.ll_pay_alipay);
        llAlipay.setOnClickListener(this);

        iv_choose_wechat = (ImageView) findViewById(R.id.iv_choose_wechat);
        iv_choose_ali = (ImageView) findViewById(R.id.iv_choose_ali);

        amount_tv = (TextView) findViewById(R.id.amount_tv);
        // 判断微信是否安装
        IWXAPI m_IWXAPI = WXAPIFactory.createWXAPI(context, null);
        m_IWXAPI.registerApp(Config.wechatId);
        if (m_IWXAPI.isWXAppInstalled() || m_IWXAPI.isWXAppInstalled()) {
            isInstallWeiChat = true;
        }


    }

    @Override
    public void onBackPressed() {

        MessageDialog.show(this, null, "确定要放弃付款吗？", getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        if (orderType == 1) {
                            Intent intent = new Intent();
                            intent.putExtra("resultCode", -2);
                            setResult(220, intent);
                        }
                        finish();
                        return false;
                    }
                });

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_back:
                MessageDialog.show(this, null, "确定要放弃付款吗？", getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                        new OnDialogButtonClickListener() {
                            @Override
                            public boolean onClick(BaseDialog baseDialog, View v) {
                                if (orderType == 1) {
                                    Intent intent = new Intent();
                                    intent.putExtra("resultCode", -2);
                                    setResult(220, intent);
                                }
                                finish();
                                return false;
                            }
                        });

                break;
            case R.id.ll_pay_weichat:
                btn_pay.setText("确认付款");
                setChooseView(iv_choose_wechat);
                currentPaymethod = getCurrentPaythod("WECHAT_SDK");
                break;
            case R.id.ll_pay_alipay:
                btn_pay.setText("确认付款");
                setChooseView(iv_choose_ali);
                currentPaymethod = getCurrentPaythod("ALIPAY_WAP");
                break;

            case R.id.btn_pay:


//                new WXPayHelper(context, "", iPayCallBack);
                requestPlayInfo(orderNo);
        }
    }


    /**
     * 设置当前支付方式model
     *
     * @param code
     */
    private Paytmethod getCurrentPaythod(String code) {
        Paytmethod currentPaymethod = null;
        for (Paytmethod model : paytmethods) {
            if (model.getCode().equals(code)) {
                currentPaymethod = model;
                break;
            }
        }
        return currentPaymethod;
    }

    /**
     * 拼接minpay的minpaydata参数
     *
     * @return
     */
    private String getMinpaydata() {
        String minpaydata = "";

        JSONObject json = new JSONObject();
        if (currentPaymethod != null) {

            try {
                json.put("paytype", currentPaymethod.getItem().getPaytype());
                json.put("payProduct", currentPaymethod.getCode());

                minpaydata = json.toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        return minpaydata;
    }


    /**
     * 设置选中效果
     *
     * @param iv
     */
    public void setChooseView(ImageView iv) {

        if (iv.getTag().toString().length() > 0) {
            return;
        }
        iv_choose_wechat.setImageResource(0);
        iv_choose_ali.setImageResource(0);
        iv.setImageResource(R.mipmap.ic_pay_check);
    }


    /**
     * 获取付款信息
     */
    private void requestPlayInfo(String orderOn) {

        if (currentPaymethod == null) {
            ToastUtils.showShort("支付方式获取失败");
            return;
        }

        Map<String, String> map = new HashMap<String, String>();
        map.put("orderno", orderOn);
        map.put("pay_type", currentPaymethod.getItem().getPay_type());
        map.put("minpaydata", getMinpaydata());
        map.put("_apiname", "pay.pay.request");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    if (currentPaymethod.getCode().equals("WECHAT_SDK")) {
                        if (isInstallWeiChat) {
                            String data = result.optString("data");
                            String id = "gh_55a696f51352";
                            String url = "/pages/pay/index?sendMsg=" + data;
                            minPay(id, url);
                        } else {
                            ToastUtils.showShort("请安装微信端!");
                        }
                    } else {
                        JSONObject data = result.getJSONObject("data");
                        String url = data.getString("url");
                        Intent intent = new Intent(mContext, Webview2Activity.class);
                        intent.putExtra("url", url);
                        intent.putExtra("isAddToken", false);
                        intent.putExtra("isAlipyWeb", true);
                        startActivityForResult(intent, 1001);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

    }


    /**
     * 敏付（微信小程序）
     */
    public void minPay(String appid, String spath) {
        LogUtils.e("跳转去微信敏付小程序支付=" + appid + "+" + spath);
        IWXAPI api = WXAPIFactory.createWXAPI(mContext, Config.wechatId);//appID
        final WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = appid;
        req.path = spath;
        api.sendReq(req);
        isCheckOrder = true;
    }


    @Override
    protected void onActivityResult(int arg0, int arg1, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(arg0, arg1, data);

        //获取web页面回调的支付参数，启动支付宝
        if (arg1 == 1001) {
            String url = data.getStringExtra("url");
            startActivityForResult(new Intent("android.intent.action.VIEW", Uri.parse(url)), 1002);
        }

        //获取从支付宝返回的事件
        if (arg0 == 1002) {
            Log.e("2255", "支付宝支付结束，需要主动查询订单支付状态");
            isCheckOrder = true;
        }

    }

//    /**
//     * 支付结果回调(敏付小程序可以用，但是如果要接web版支付宝的话，就不行了，不如统一用主动查询)
//     */
//    IPayCallBack iPayCallBack = new IPayCallBack() {
//
//        @Override
//        public void payCallBack(int p_result) {
//            // TODO Auto-generated method stub
//            if (p_result == -2) {
//                return;
//            }
//            Intent intent = new Intent();
//            intent.putExtra("resultCode", p_result);
//            setResult(220, intent);
//            finish();
//        }
//    };


    /**
     * 获取支付配置
     */
    private void requestPlayMethod() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("orderno", orderNo);
        map.put("_apiname", "pay.pay.paytmethod");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject jsonData = result.getJSONObject("data");
                    JSONArray jsonPaytmethod = jsonData.getJSONArray("paytmethod");

                    paytmethods = GsonUtils
                            .fromJsonList(jsonPaytmethod.toString(), new TypeToken<List<Paytmethod>>() {
                            }.getType());

                    for (int i = 0; i < paytmethods.size(); i++) {
                        Paytmethod model = paytmethods.get(i);

                        if (model.getCode().equals("WECHAT_SDK")) {
                            //是否支持微信支付
                            if (model.getIsshow().equals("1")) {
                                llWeichat.setVisibility(View.VISIBLE);
                                if (currentPaymethod == null) {
                                    setChooseView(iv_choose_wechat);
                                    currentPaymethod = model;
                                }
                            } else {
                                llWeichat.setVisibility(View.GONE);
                            }
                        }

                        if (model.getCode().equals("ALIPAY_WAP")) {
                            //是否支持支付宝
                            if (model.getIsshow().equals("1")) {
                                llAlipay.setVisibility(View.VISIBLE);
                                if (currentPaymethod == null) {
                                    setChooseView(iv_choose_ali);
                                    currentPaymethod = model;
                                }
                            } else {
                                llAlipay.setVisibility(View.GONE);
                            }
                        }

                    }

                    String pay_amount = jsonData.optString("pay_amount");
                    if (!TextUtils.isEmpty(pay_amount)) {
                        amount_tv.setText("¥" + pay_amount);
                    } else {
                        amount_tv.setText("¥0");
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 查询订单状态
     */
    private void requestCheckOrder() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("orderno", orderNo);
        map.put("_apiname", "order.index.orderstatus");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject jsonData = result.getJSONObject("data");
                    //{"code":"200","msg":"success","data":{"pay_status":"0"}}
                    String pay_status = jsonData.optString("pay_status");
                    int p_result = -1;
                    switch (pay_status) {
                        case "1":
                            p_result = 0;
                            break;
                        default:
                            p_result = -1;
                            break;
                    }
                    Intent intent = new Intent();
                    intent.putExtra("resultCode", p_result);
                    setResult(220, intent);
                    finish();

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.e("2255", "收银台恢复了 isCheckOrder=" + isCheckOrder);
        if (isCheckOrder) {
            LoadingDialog.getInstance(this).setMessage("结果查询中").show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    LoadingDialog.dismissDialog();
                    requestCheckOrder();
                }
            }, 1500);
        } else {
            requestPlayMethod();
        }

    }


    /**
     * 支付方式model
     */
    public class Paytmethod {


        /**
         * isshow : 1
         * code : ALIPAY_WAP
         * payname : 支付宝支付
         * canchoose : 1
         * icon : http://zscloudnew.oss-cn-shenzhen.aliyuncs.com/pay/ali.png?x-oss-process=image/quality,q_80
         * status :
         * item : {"paytype":"gateway","pay_type":"minpay"}
         */

        private String isshow;
        private String code;
        private String payname;
        private String canchoose;
        private String icon;
        private String status;
        private ItemBean item;

        public String getIsshow() {
            return isshow;
        }

        public void setIsshow(String isshow) {
            this.isshow = isshow;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getPayname() {
            return payname;
        }

        public void setPayname(String payname) {
            this.payname = payname;
        }

        public String getCanchoose() {
            return canchoose;
        }

        public void setCanchoose(String canchoose) {
            this.canchoose = canchoose;
        }

        public String getIcon() {
            return icon;
        }

        public void setIcon(String icon) {
            this.icon = icon;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public ItemBean getItem() {
            return item;
        }

        public void setItem(ItemBean item) {
            this.item = item;
        }

        public class ItemBean {
            /**
             * paytype : gateway
             * pay_type : minpay
             */

            private String paytype;
            private String pay_type;

            public String getPaytype() {
                return paytype;
            }

            public void setPaytype(String paytype) {
                this.paytype = paytype;
            }

            public String getPay_type() {
                return pay_type;
            }

            public void setPay_type(String pay_type) {
                this.pay_type = pay_type;
            }
        }
    }

}
